package chapter12.eg2;

import io.netty.buffer.ByteBuf;
import java.io.IOException;
import org.jboss.marshalling.ByteInput;
import org.jboss.marshalling.MarshallerFactory;
import org.jboss.marshalling.Marshalling;
import org.jboss.marshalling.MarshallingConfiguration;
import org.jboss.marshalling.Unmarshaller;

public class MarshallingDecoder {

  private final Unmarshaller unmarshaller;

  public MarshallingDecoder() throws IOException {
    final MarshallerFactory marshallerFactory = Marshalling.getProvidedMarshallerFactory("serial");
    final MarshallingConfiguration configuration = new MarshallingConfiguration();
    configuration.setVersion(5);
    unmarshaller = marshallerFactory.createUnmarshaller(configuration);
  }

  protected Object decode(ByteBuf in) throws IOException, ClassNotFoundException {
    int objectSize = in.readInt();
    ByteBuf buf = in.slice(in.readerIndex(), objectSize);
    ByteInput input = new MyByteBufByteInput(buf);
    try {
      unmarshaller.start(input);
      Object obj = unmarshaller.readObject();
      unmarshaller.finish();
      in.readerIndex(in.readerIndex() + objectSize);
      return obj;
    } finally {
      unmarshaller.close();
    }
  }
}
